package com.sp.app.filter;

import com.sp.app.domain.User;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter {

    public void destroy() {
        // TODO Auto-generated method stub

    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc)
            throws IOException, ServletException {
        // TODO Auto-generated method stub

        HttpServletRequest servletRequest = (HttpServletRequest) req;
        HttpServletResponse servletResponse = (HttpServletResponse) res;
        HttpSession session = servletRequest.getSession();

        String path = servletRequest.getRequestURI();

        User user = (User) session.getAttribute("user");

        if(path.indexOf("/index") > -1) {
            fc.doFilter(servletRequest, servletResponse);
            return;
        }

        if(path.indexOf("/Login") > -1) {
            fc.doFilter(servletRequest, servletResponse);
            return;
        }

        if(path.contains(".css") || path.contains(".js")) {
            fc.doFilter(servletRequest, servletResponse);
            return;
        }
        if (user == null ) {
            // 跳转到登陆页?
            servletResponse.sendRedirect("/ChooseCourse/index");
            servletRequest.getSession().setAttribute("info", "请先登陆本系统再进行操作！");
        } else {
            // 已经登陆,继续此次请求
            fc.doFilter(req, res);
        }

    }

    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }

}
